package cn.com.zpark;

import cn.com.zpark.pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @PackageName: cn.com.zpark
 * @ClassName: JDBC_05_Select
 * @Description: JDBC查询数据
 * @author: RZS
 * @date: 2021/10/25  15:52
 */
public class JDBC_06_Select {
    public static void main(String[] args) {
        String url = "jdbc:mysql://192.168.80.142:3306/mydb1?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8";
        Connection conn = null;
        Statement stat = null;
        ResultSet res = null;
        try {
            // 1、注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2、获取连接
            conn = DriverManager.getConnection(url, "root", "root");
            // 3、创建statement对象
            stat = conn.createStatement();
            // 4、编写sql语句
            String sql = "select * from user";
            // 5、执行sql
            res = stat.executeQuery(sql);

            // 创建集合对象，用于存放user数据
            List<User> list = new ArrayList<>();

            // 6、获取执行结果
            while (res.next()) {
                // 创建user对象
                User user = new User();
                // 获取id值
                Integer id = res.getInt("id");
                // 设置user对象的ID属性
                user.setId(id);
                // 获取name字段的值
                String name = res.getString("name");
                // 设置user对象的name属性
                user.setName(name);

                String pwd = res.getString("pwd");
                user.setPwd(pwd);

                Double money = res.getDouble("money");
                user.setMoney(money);

                // 将user对象添加到list集合中去
                list.add(user);
            }

            System.out.println(list);
            
            // 遍历集合
            for (User user : list) {
                System.out.println(user.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 7、关闭连接
            if (res != null) {
                try {
                    res.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stat != null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
